<template>
  <div class="container">
    <div class="box">
      <div class="inner-box">
        <div class="control-row">
          <div class="form-items">
            <el-radio-group v-model="tabPosition" @change="fetch">
              <el-radio-button label="年度">年度</el-radio-button>
              <el-radio-button label="季度">季度</el-radio-button>
              <el-radio-button label="月度">月度</el-radio-button>
              <el-radio-button label="近7日" selected>近7日</el-radio-button>
            </el-radio-group>
            <el-date-picker
              v-if="yearOpen"
              v-model="selectedYear"
              type="year"
              placeholder="Pick a year"
              format="YYYY"
              value-format="YYYY"
              style="width: 100px"
              @change="fetch"
            />
            <el-date-picker
              v-if="monthOpen"
              v-model="selectedMonth"
              type="month"
              placeholder="Pick a month"
              format="YYYY/MM"
              value-format="YYYY-MM"
              style="width: 150px"
              @change="fetch"
            />
            <el-select
              v-show="quarterOpen"
              v-model="selectedQuarter"
              class="m-2"
              placeholder="Select"
              style="width: 100px"
              @change="fetch"
            >
              <el-option
                v-for="item in quarters"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <el-button
            type="success"
            icon="Download"
            style="margin-right: 5px"
            plain
            @click="exportExcel()"
            >导出Excel</el-button
          >
        </div>
      </div>
      <div class="inner-box">
        <el-col
          v-for="(item, index) in chartData"
          :key="index"
          v-motion
          class="chart-col"
          :xs="24"
          :sm="12"
          :md="12"
          :lg="12"
          :initial="{
            opacity: 0,
            y: 100
          }"
          :enter="{
            opacity: 1,
            y: 0,
            transition: {
              delay: 80
            }
          }"
        >
          <el-card class="line-card" shadow="never">
            <div class="flex justify-between">
              <span class="text-md font-medium">{{ item.name }}</span>
            </div>
            <!-- 修改布局容器 -->
            <div class="chart-container">
              <div class="data-column">
                <ReNormalCountTo
                  :duration="item.duration"
                  :fontSize="'1.6em'"
                  :startVal="100"
                  :endVal="item.value"
                />
              </div>
              <div class="chart-column">
                <ChartLine
                  v-if="item.data.length > 1"
                  :color="item.color"
                  :data="item.data"
                />
                <ChartRound v-else />
              </div>
            </div>
          </el-card>
        </el-col>
      </div>
    </div>

    <div class="box">
      <el-card>
        <div id="chart4" ref="chartDom4" class="chart" />
      </el-card>
    </div>
    <div class="box">
      <el-card>
        <div id="chart2" ref="chartDom2" class="chart" />
      </el-card>
    </div>
    <div class="box">
      <el-card>
        <div id="chart1" ref="chartDom1" class="chart" />
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { markRaw } from "vue";
import ReCol from "@/components/ReCol";
import { useDark } from "../analysis/utils";
import WelcomeTable from "./components/table/index.vue";
import { ReNormalCountTo } from "@/components/ReCountTo";
import { useRenderFlicker } from "@/components/ReFlicker";
import Segmented, { type OptionsType } from "@/components/ReSegmented";
import { chartData } from "../analysis/data";
import { ChartBar, ChartLine, ChartRound } from "./components/charts";

import {
  exportReport,
  getPercentageOfTurnover,
  getSalesVolume,
  getTodayTurnover,
  getTotalTurnover,
  getTurnover
} from "@/api/roomanalysis";
import { tr } from "@faker-js/faker";
import * as echarts from "echarts";
import { onMounted, ref } from "vue";
import dayjs from "dayjs";
import { c } from "node_modules/vite/dist/node/types.d-aGj9QkWt";
import { log } from "node:console";
import { text } from "node:stream/consumers";
onMounted(() => {
  if (chartDom1.value) {
    myChart1 = echarts.init(chartDom1.value);
    myChart1.setOption(option1, { notMerge: true });
  }
  if (chartDom2.value) {
    myChart2 = echarts.init(chartDom2.value);
    myChart2.setOption(option2);
  }
  if (chartDom3.value) {
    myChart3 = echarts.init(chartDom3.value);
    myChart3.setOption(option3);
  }
  if (chartDom4.value) {
    myChart4 = echarts.init(chartDom4.value);
    myChart4.setOption(option4);
  }
  const currentDate = dayjs().format("YYYY-MM-DD");
  getVolume(currentDate);
  getTodayTurnover(dayjs().format("YYYY-MM-DD")).then(response => {
    // TodayTurnover.value = response.data;
    chartData.value[1].value = response.data;
  });
  getTotalTurnover().then(response => {
    // TotalTurnover.value = response.data;
    chartData.value[0].value = response.data;
    console.log("营业额" + chartData.value[0].value);
  });
});
async function exportExcel() {
  /** 调用后端分页查询接口 */
  exportReport().then(response => {
    console.log(response);
    const blob = new Blob([response as any], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    let url = URL.createObjectURL(blob);
    var link = document.createElement("a");
    document.body.appendChild(link);
    link.href = url;
    link.download = "运营数据报表.xlsx";
    link.click();
    // document.body.removeChild(link);
    URL.revokeObjectURL(url);
  });
}
const { isDark } = useDark();
const totalDate = ref<string>("2025-04-17");
const TodayTurnover = ref<number>(500);
const TotalTurnover = ref<number>(4000);
function fetch() {
  switch (tabPosition.value) {
    case "近7日":
      yearOpen.value = false;
      monthOpen.value = false;
      quarterOpen.value = false;
      totalDate.value = dayjs().format("YYYY-MM-DD");
      break;
    case "月度":
      yearOpen.value = false;
      monthOpen.value = true;
      quarterOpen.value = false;
      totalDate.value = selectedMonth.value.concat("-01");
      break;
    case "季度":
      yearOpen.value = true;
      monthOpen.value = false;
      quarterOpen.value = true;
      totalDate.value =
        selectedYear.value + "-" + selectedQuarter.value + "-01";
      break;
    case "年度":
      yearOpen.value = true;
      monthOpen.value = false;
      quarterOpen.value = false;
      totalDate.value = selectedYear.value + "-01-01";
      break;
  }
  getVolume(totalDate.value);
}
const tabPosition = ref("近7日");
const yearOpen = ref<boolean>(false);
const monthOpen = ref<boolean>(false);
const quarterOpen = ref<boolean>(false);
const years = ref(
  [...Array(2).keys()].map(year => new Date().getFullYear() - year)
);
const quarters = ref([
  { value: "01", label: "第1季度" },
  { value: "04", label: "第2季度" },
  { value: "07", label: "第3季度" },
  { value: "10", label: "第4季度" }
]);
const months = ref(
  [...Array(12).keys()].map(month => {
    // 将月份格式化为两位数，例如1变为"01"
    const formattedMonth = (month + 1).toString().padStart(2, "0");
    return {
      value: formattedMonth, // 格式化后的月份作为value
      label: month + 1 // 可以根据需要设置label
    };
  })
);
const weeks = ref([...Array(7).keys()].map(week => `Day ${week + 1}`));

const selectedYear = ref("2025");
const selectedQuarter = ref(quarters.value[0].value);
const selectedMonth = ref("2025-01");
const getVolume = async (totalDate: string) => {
  console.log("totalDate", totalDate);
  try {
    getSalesVolume(tabPosition.value, totalDate).then(response => {
      option1.dataset[0].source = response.data;
      if (myChart1) {
        if (chartDom1.value) {
          console.log("getVolumechartDom1", chartDom1.value);
          // myChart1 = echarts.init(chartDom1.value);
          myChart1.setOption(option1, { notMerge: true });
        }
        // console.log("getVolumechartDom1", chartDom1.value);
        // myChart1 = echarts.init(chartDom1.value);
        // myChart1.setOption(option1, { notMerge: true });
        // myChart1.showLoading();
        // setTimeout(() => myChart1?.hideLoading(), 200);
      }
    });
    getTurnover(tabPosition.value, totalDate).then(response => {
      option2.xAxis.data = response.data[0];
      option2.series = response.data[1];
      if (myChart2) {
        myChart2 = echarts.init(chartDom2.value);
        myChart2.setOption(option2, { notMerge: true });
        myChart2.showLoading();
        setTimeout(() => myChart2?.hideLoading(), 200);
      }
    });
    getPercentageOfTurnover(tabPosition.value, totalDate).then(response => {
      option4.series[0].data = response.data;
      if (myChart4) {
        myChart4 = echarts.init(chartDom4.value);
        myChart4.setOption(option4, { notMerge: true });
        myChart4.showLoading();
        setTimeout(() => myChart4?.hideLoading(), 200);
      }
    });
  } catch (error) {
    console.error(error);
  }
};
type EChartsOption = echarts.EChartsOption;

const chartDom1 = ref<HTMLElement | null>(null);
const chartDom2 = ref<HTMLElement | null>(null);
const chartDom3 = ref<HTMLElement | null>(null);
const chartDom4 = ref<HTMLElement | null>(null);

let myChart1: echarts.ECharts | null = null;
let myChart2: echarts.ECharts | null = null;
let myChart3: echarts.ECharts | null = null;
let myChart4: echarts.ECharts | null = null;

const option1: EChartsOption = {
  title: {
    text: "房型销量排行",
    left: "center"
  },
  dataset: [
    {
      dimensions: ["name", "amount"],
      source: [
        ["房型一", 315],
        ["房型二", 351],
        ["房型三", 287]
      ]
    },
    {
      transform: {
        type: "sort",
        config: { dimension: "amount", order: "asc" }
      }
    }
  ],

  xAxis: { name: "销售量" },
  yAxis: { name: "房型", type: "category" },
  series: {
    type: "bar",
    encode: { x: "amount", y: "name" },
    datasetIndex: 1,
    label: {
      show: true,
      position: "right",
      valueAnimation: true
    }
  },
  grid: {
    left: "1%", // 调整左边界
    right: "10%", // 调整右边界
    bottom: "20%", // 调整底边界
    containLabel: true // 包含标签
  }
};
const option2 = {
  title: {
    text: "房型营业额",
    left: "center"
  },
  xAxis: {
    name: "日期",
    type: "category",
    data: [
      "01",
      "02",
      "03",
      "04",
      "05",
      "06",
      "07",
      "08",
      "09",
      "10",
      "11",
      "12"
    ]
  },
  yAxis: {
    name: "营业额(元)",
    type: "value"
  },
  series: [
    {
      name: "经济单人间",
      type: "line",
      data: [0, 0, 1620, 2570, 0, 0, 0, 0, 0, 0, 0, 0]
    },
    {
      name: "经济双人间（大床房）",
      type: "line",
      data: [0, 0, 1524, 1530, 0, 0, 0, 0, 0, 0, 0, 0]
    },
    {
      name: "经济双人间（双床房）",
      type: "line",
      data: [0, 0, 0, 1320, 0, 0, 0, 0, 0, 0, 0, 0]
    }
  ]
};
const option3 = {
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: "bar"
    }
  ]
};
const option4 = {
  title: {
    text: "房型营业额占比",
    left: "center"
  },
  tooltip: {
    trigger: "item"
  },
  series: [
    {
      type: "pie",
      radius: "50%",
      data: [
        {
          value: 4190,
          name: "经济双人间（大床房）"
        },
        {
          value: 3054,
          name: "经济单人间"
        },
        {
          value: 1320,
          name: "经济双人间（双床房）"
        }
      ],
      label: {
        show: true,
        formatter: ({ name, value, percent }) =>
          `${name}\n${value}¥\n ${percent}%`, // 换行显示
        fontSize: 12,
        fontWeight: "bold"
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      }
    }
  ]
};
</script>

<style scoped>
.chart-container {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
  min-width: 0; /* 解决flex溢出问题 */
  height: calc(100% - 40px); /* 扣除标题区域高度 */
  min-height: 0;
  margin-top: 12px;
}

.chart {
  box-sizing: border-box; /* 包含 padding 和 border */
  width: 100%;
  min-width: 0; /* 允许内容溢出时缩小 */
  height: 300px;
  padding: 5px;
  margin-bottom: 16px;
  margin-left: 20px;
}

.grid-content {
  min-height: 36px;
  border-radius: 4px;
}

.equal-height {
  height: 100%; /* 设置为100%以填充父容器高度 */
}

/* 由于el-card默认有内边距，可能需要设置最小高度来保证一致性 */
.el-card {
  min-height: 400px; /* 根据实际内容调整最小高度 */
}

/* 统计数字盒子样式 */
.statistic-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center; /* 文字居中 */
}

/* 放大字体 */
.large-text .el-statistic__content {
  font-size: 3px; /* 按需调整 */
}

/* 控制区域盒子 */
.control-box {
  display: flex; /* 添加flex布局 */
  flex-flow: row wrap; /* 水平排列 */ /* 允许换行 */
  align-items: center; /* 垂直居中 */
  height: 100%;
}

:deep(.el-card) {
  --el-card-border-color: none;

  /* 解决概率进度条宽度 */
  .el-progress--line {
    width: 85%;
  }

  /* 解决概率进度条字体大小 */
  .el-progress-bar__innerText {
    font-size: 15px;
  }

  /* 隐藏 el-scrollbar 滚动条 */
  .el-scrollbar__bar {
    display: none;
  }

  /* el-timeline 每一项上下、左右边距 */
  .el-timeline-item {
    margin: 0 6px;
  }
}

.main-content {
  margin: 20px 20px 0 !important;
}

/* 必须添加的样式 */
.el-card.line-card {
  /* 覆盖默认padding */
  --el-card-padding: 0 !important;

  /* 解除内部元素限制 */
  .el-card__body {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0 !important;
  }
}

.card-inner {
  flex: 1;
  min-height: 0; /* 关键：允许内容区收缩 */
  padding: 8px; /* 内部间距 */
  overflow: hidden; /* 控制内容溢出 */
}

.container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  max-width: 98%;
  padding: 10px;
  background: #f0f3f3;
  border-radius: 2px;
}

/* 外层盒子强化尺寸控制 */
.box {
  box-sizing: border-box;
  flex-shrink: 0; /* 禁止压缩 */
  padding: 0;
  overflow: hidden;
  background: #fff;
  border-radius: 5px;
}

/* 第一个复合盒子 */
.box:nth-child(1) {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: calc(50% - 5px);
  height: 275px; /* 严格固定高度 */
}

/* 内部子盒子严格尺寸 */
.inner-box {
  box-sizing: border-box;
  width: 100%;
  height: 70px; /* 初始高度 */
  padding: 5px;
  background: #fff;
}

/* 通过 min/max-height 双重锁定尺寸 */
.inner-box:nth-child(1) {
  min-height: 0;
  max-height: 100px;
}

.inner-box:nth-child(2) {
  display: flex;
  width: 100%;
  height: 190px;
  min-height: 190px; /* 与height保持一致 */
  max-height: 190px; /* 取消200px上限 */
  overflow: visible; /* 允许内容扩展 */
}

/* 其他外层盒子尺寸锁定 */
.box:nth-child(2) {
  width: calc(50% - 5px);
  height: 275px;
  min-height: 100px;
  max-height: 275px;
}

.box:nth-child(3) {
  width: calc(50% - 5px);
  height: 275px;
  min-height: 120px;
  max-height: 275px;
}

.box:nth-child(4) {
  width: calc(50% - 5px);
  height: 275px;
  min-height: 100px;
  max-height: 275px;
}

.chart-col {
  overflow: hidden; /* 隐藏溢出的内容 */
}

.control-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.form-items {
  display: flex;
  flex-shrink: 0;
  gap: 8px;
  align-items: center;
}

.radio-group {
  flex-shrink: 0;
  margin-right: 8px;
}

.date-pickers {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 紧凑型选择器样式 */
.compact-picker,
.compact-select {
  flex-shrink: 0;
  margin: 0 !important;
}

/* 固定右侧按钮 */
.fixed-button {
  flex-shrink: 0;
  margin-left: auto !important;
}

/* 防止元素缩放 */
.el-radio-button__inner,
.el-date-editor,
.el-select {
  flex-shrink: 0;
}

/* 统一元素高度 */
.el-date-editor,
.el-button {
  height: 32px !important;
}

.data-column,
.chart-column {
  flex: 1 1 50%; /* 等分容器 */
  min-width: 0; /* 允许内容收缩 */
  height: 100% !important; /* 继承父容器高度 */
}

/* 图表容器尺寸控制 */
.chart-column > div {
  width: 100% !important;
  height: 100% !important;
  min-height: 120px;
}

/* 覆盖ElementUI默认样式 */
.line-card {
  width: 100% !important;
}

.line-card .el-card__body {
  padding: 16px !important;
}
</style>
